package com.tanjor.sys.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.tanjor.sys.entity.SysRole;
import com.tanjor.sys.dubbo.dto.SysRoleDTO;

import com.tanjor.sys.mapper.SysRoleMapper;
import com.tanjor.sys.service.interfaces.ISysRoleService;
import com.tanjor.user.dubbo.dto.SysUserRoleDTO;
import com.tanjor.user.dubbo.impl.interfaces.ISysUserDubbo;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.tanjor.common.datatable.ColumnFilter;
import com.tanjor.common.datatable.PageReq;
import com.tanjor.common.datatable.PageResp;
import com.tanjor.common.exception.BusinessException;
import com.tanjor.common.util.ObjectUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.toolkit.IdWorker;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Liuwy
 * @since 2017-04-02
 */
@Service("SysRoleServiceImpl")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
	
	@Resource
	private ISysUserDubbo sysUserDubbo;
	/**
	 *  List<SysRole> to List<SysRoleDTO>
	 */
	private  List<SysRoleDTO> copyList(List<SysRole> list){
		List<SysRoleDTO> entityDTOs = new ArrayList<SysRoleDTO>();
		if(list!=null){
			for(SysRole entity:list){
				SysRoleDTO entityDTO = new SysRoleDTO();
				ObjectUtil.copy(entity,entityDTO);
				entityDTOs.add(entityDTO);
			}
		}
		return entityDTOs;
	}
	
	/**
	 * 分页入参构造器
	 * @param pageReq
	 * @return
	 */
	private EntityWrapper<SysRole> createWrapper(PageReq pageReq){
		EntityWrapper<SysRole> wrapper = new EntityWrapper<SysRole>();
		if(pageReq.getColumnFilters()!=null){
			for(ColumnFilter columnFilter:pageReq.getColumnFilters()){
				//按需求构造入参
				if(columnFilter.getName().equals("code")){
					wrapper.and("code like {0}", columnFilter.getValue());
				}else if(columnFilter.getName().equals("name")){
					wrapper.and("name like {0}", columnFilter.getValue());
				}
			}
		}
		return wrapper;
	}
	
	@Override
	public PageResp findPage(PageReq pageReq) {
		// TODO Auto-generated method stub
		PageResp page = new PageResp();
		//请求标志位
		page.setDraw(pageReq.getDraw());
		//构造条件
		EntityWrapper<SysRole> wrapper = createWrapper(pageReq);
		//统计总数
		Integer totalRows = this.baseMapper.selectCount(wrapper);
		//排序	
		if(StringUtils.isNotBlank(pageReq.getOrderBy())){
			wrapper.orderBy(pageReq.getOrderBy(), pageReq.getIsAsc());
		}
		//查询	
		List<SysRoleDTO> list = findPage(wrapper, pageReq.getStart(), pageReq.getLength());				
		
		//构造返回
		page.setData(list);
		page.setRecordsFiltered(totalRows);
		page.setRecordsTotal(totalRows);
		return page;
	}
	
	@Override
	public List<SysRoleDTO> findPage(Wrapper<SysRole> wrapper,int start,int limit) {
		// TODO Auto-generated method stub
		List<SysRole> list = baseMapper.selectPage(new RowBounds(start, limit), wrapper);
		return this.copyList(list);
	}
	
	@Override
	public Map<String,Object> insert(SysRoleDTO entityDTO) throws BusinessException{
		// TODO Auto-generated method stub	
		Map<String,Object> map = new HashMap<String,Object>();
		EntityWrapper<SysRole> wrapper = new EntityWrapper<SysRole>();
		wrapper.and("code={0}", entityDTO.getCode());
		int num = this.baseMapper.selectCount(wrapper);
		if(num<1){
			entityDTO.setId(""+IdWorker.getId());
			SysRole entity = new SysRole();
			ObjectUtil.copy(entityDTO,entity);
			this.insert(entity);
			map.put("result", true);
		}else{
			map.put("result", false);
			map.put("msg", "该角色编码已经存在，请重新输入！");
		}
		return map;
	}
	
	@Override
	public Map<String,Object> update(SysRoleDTO entityDTO) throws BusinessException{
		Map<String,Object> map = new HashMap<String,Object>();
		// TODO Auto-generated method stub
		SysRole entity = new SysRole();
		ObjectUtil.copy(entityDTO,entity);
		this.updateById(entity);
		map.put("result", true);
		return map;
	}	
	
	@Override
	public Map<String, Object> delById(Serializable id) throws BusinessException {
		// TODO Auto-generated method stub
		Map<String,Object> map = new HashMap<String,Object>();
		this.deleteById(id);
		map.put("result", true);	
		return map;
	}
	
	@Override
	public SysRoleDTO findById(Serializable id){
		// TODO Auto-generated method stub
		SysRoleDTO entityDTO = new SysRoleDTO();
		SysRole entity = this.selectById(id);
		ObjectUtil.copy(entity,entityDTO);
		return entityDTO;
	}

	@Override
	public List<Map<String, Object>> findTreeByUser(String userId) {
		// TODO Auto-generated method stub
		List<Map<String,Object>> roles = new ArrayList<Map<String,Object>>();
		List<SysRole> sysRoles = findAll();
		List<SysUserRoleDTO> userRoles = sysUserDubbo.findByUserId(userId);
		for(SysRole sysRole:sysRoles){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("id", sysRole.getCode());
			map.put("name", sysRole.getName());
			map.put("checked", hasPermission(sysRole.getCode(),userRoles));
			roles.add(map);
		}
		return roles;
	}
	
	private List<SysRole> findAll(){
		EntityWrapper<SysRole> wrapper = new EntityWrapper<SysRole>();
		return this.baseMapper.selectList(wrapper);
	}
	
	/* *//**
     * 判断是否拥有权限
     * @param roleCode
     * @param userRoles
     * @return
     */
    private boolean hasPermission(String roleCode,List<SysUserRoleDTO> userRoles){
		boolean result = false;
		for(SysUserRoleDTO userRole:userRoles){
			if(roleCode.equals(userRole.getRoleCode())){
				result = true;
				break;
			}
		}
		return result;
	}

	@Override
	public SysRoleDTO findByCode(String code) {
		// TODO Auto-generated method stub
		EntityWrapper<SysRole> wrapper = new EntityWrapper<SysRole>();
		wrapper.and("code={0}",code);
		SysRole entity = this.selectOne(wrapper);
		SysRoleDTO entityDTO = new SysRoleDTO();
		ObjectUtil.copy(entity,entityDTO);
		return entityDTO; 
	}
    
	
}
